package com.foxzzz.datamemory.controller;


import com.foxzzz.datamemory.entity.BlobSave;
import com.foxzzz.datamemory.service.BlobSaveService;
import com.foxzzz.datamemory.util.BlobUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/blobSave")
public class BlobSaveController {
    @Autowired
    private BlobSaveService blobSaveService;
    @Autowired
    private BlobUtil blobUtil;

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String id = null;
        try {
            id = blobSaveService.upload(fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return id;
    }

    @GetMapping("/download")
    public void download(String id, HttpServletResponse response, HttpServletRequest request) {
        BlobSave byId = blobSaveService.getById(id);
        if (byId == null) {
            return;
        }
        String fileName = byId.getFileName();
        try {
            String range = request.getHeader("Range");
            ServletOutputStream out = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
            byte[] buffer = new byte[1024];
            int count = 0;
            InputStream stream = blobUtil.getStream(byId.getBlob());
            while ((count = stream.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            stream.close();
        } catch (IOException e) {

        }
    }

    @GetMapping("/list")
    public List<BlobSave> list() {
        return blobSaveService.list();
    }
}
